﻿using Airon.Dapper.Internal;
using Airon.DatabaseAccessor;
using Airon.Extras.DatabaseAccessor.Dapper.Internal;
using System;
using System.Data;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// Dapper 拓展类
    /// </summary>
    public static class DapperServiceCollectionExtensions
    {
        /// <summary>
        /// 添加 Dapper 拓展   单数据库
        /// </summary>
        /// <param name="services"></param>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="sqlProvider"> <see cref="Furion.DatabaseAccessor.SqlProvider"/> 类型</param>
        /// <returns></returns>
        public static IServiceCollection AddDapper(this IServiceCollection services, string connectionString, string sqlProvider)
        {
            // 获取数据库类型
            var dbConnectionType = SqlProvider.GetDbConnectionType(sqlProvider);

            // 创建数据库连接对象  单数据库 的时候 直接获取数据库连接
            
            services.AddScoped(u =>
            {
                var dbConnection = Activator.CreateInstance(dbConnectionType, new[] { connectionString }) as IDbConnection;
               
                if (dbConnection.State != ConnectionState.Open) dbConnection.Open();

                return dbConnection;
            });
            // 注册非泛型仓储
            services.AddScoped<IDapperRepository, DapperRepository>();

            // 注册 Dapper 仓储
            services.AddScoped(typeof(IDapperRepository<>), typeof(DapperRepository<>));

            return services;
        }

        /// <summary>
        /// 添加 Dapper 拓展   多数据库
        /// </summary>
        /// <param name="services"></param>
        /// <param name="connectionStrings">连接字符串 添加读写分离支持</param>
        /// <param name="sqlProvider"> <see cref="Furion.DatabaseAccessor.SqlProvider"/> 类型</param>
        /// <returns></returns>
        public static IServiceCollection AddDapper(this IServiceCollection services,string sqlProvider, SqlDataBaseConfig[] connectionStrings)
        {
            //多数据库的时候 仅仅设置数据库连接字符串  在每个数据库操作之前进行即时获取数据库连接
            services.AddScoped(u=> {
                return new SqlDataBaseConfigConstructor()
                {
                    sqlProvider = sqlProvider,
                    configs = connectionStrings
                };
            });
            // 注册非泛型仓储
            services.AddScoped<IDapperRepository, DapperRepository>();

            // 注册 Dapper 仓储
            services.AddScoped(typeof(IDapperRepository<>), typeof(DapperRepository<>));

            return services;
        }


    }
}